#coding:utf-8
#author: leanse

"""
kuaipan API 接口文件
"""

import re
import sys
from http_client import http_client
from http_client import ErrorRespon
from session import KuaipanSession
from session import to_str
from session import log

def format_path(path):
    if not path:
        return path

    path = re.sub(r'/+', '/', path)
    if path == '/':
        return ""
    else:
        return '/' + path.strip('/') 

class KuaipanAPI():
    def __init__(self, session):
        self.session = session#授权过的session
        self.host = None
   
    def request(self, target, params = None, server = 'API', catchErrorRespon=True):
        host = {'API'     : self.session.API_HOST,
                'CONTENT' : self.session.CONTENT_HOST,
                'CONV'    : self.session.CONV_HOST}
        try:
            return self.session.request(host[server], target, params)
        except ErrorRespon as  e:
            if catchErrorRespon or e.code==401 :
                print(e.code,e.reason)
                sys.exit(2);
            else:
                raise
        
    def account_info(self):
        return self.request("/1/account_info")

    def metadata(self, path, list = True):
        target = "/1/metadata/%s%s" % (self.session.root, format_path(path))
        params = dict(list = ("true" if list else "false"),sort_by = 'size')
        return self.request(target, params)
        
    def is_exist(self, path, type=""):
        '''这里出现其它错误也可能返回False'''
        target = "/1/metadata/%s%s" % (self.session.root, format_path(path))
        params = dict(list = 'false')
        try:
            rel= self.request(target, params, catchErrorRespon=False)
            if rel.get('is_deleted')==False:
                return True
        except ErrorRespon as  e:
            return False
        return False
        
    def shares(self, path, access_code=None):
        target = "/1/shares/%s%s" % (self.session.root, format_path(path))
        params = ()
        if access_code:
            params = dict(access_code = access_code)
        return self.request(target, params)

    def create_folder(self, path):
        params = dict(root = self.session.root, path = to_str(path))
        return self.request("/1/fileops/create_folder", params)

    def delete(self, path):
        params = dict(root = self.session.root, path = to_str(path))
        return self.request("/1/fileops/delete", params)

    def move(self, from_path, to_path):
        params = dict(root = self.session.root, from_path = to_str(from_path), to_path = to_str(to_path))
        return self.request("/1/fileops/move", params)

    def copy(self, from_path, to_path):
        params = dict(root = self.session.root, from_path = to_str(from_path), to_path = to_str(to_path))
        return self.request("/1/fileops/copy", params)

    def get_upload_locate(self):
        ret = self.request("/1/fileops/upload_locate", server = 'CONTENT')
        return ret['url']

    def upload_file(self, path, data, overwrite):
        if not self.host:
            self.host = self.get_upload_locate()
        overwrite = "True" if overwrite else "False"
        params = dict(root = self.session.root, path = to_str(path), overwrite = overwrite)
        url = self.session.build_url(self.host, "1/fileops/upload_file", params,'POST' )
        try:    
            ret = http_client.MultiPartPost(url, data, "kfile")
            return ret
        except ErrorRespon as  e:
            print(e.code,e.reason)
            sys.exit(2);

    def download_file(self, path):
        params = dict(root = self.session.root, path = to_str(path))
        url = self.session.build_url(self.session.CONTENT_HOST, "/1/fileops/download_file",  params ,'GET')
        try:
            return http_client.DownloadFile(url)
        except ErrorRespon as  e:
            print(e.code,e.reason)
            sys.exit(2);
            
    def thumbnail(self, path, width, height):
        params = dict(root = self.session.root, path = to_str(path), width = to_str(width), height = to_str(height))
        url = self.session.build_url(self.session.CONV_HOST, "/1/fileops/thumbnail", params, 'POST')
        try:    
            ret = http_client.ConverFile(url)
            return ret
        except ErrorRespon as  e:
            print(e.code,e.reason)
            sys.exit(2);

    def document_view(self, path, view, type, zip = 0):
        params = dict(root = self.session.root, path = to_str(path), view = view, type = type, zip = to_str(zip))
        url = self.session.build_url(self.session.CONV_HOST, "/1/fileops/documentView",params ,'POST')
        ret = http_client.ConverFile(url)
        return ret
